package com.easipass.business.service.impl;

import com.easipass.business.dto.page.MyNotesDTO;
import com.easipass.business.po.MyNotesPO;
import com.easipass.business.repository.MyNoteDao;
import com.easipass.business.service.MyNoteService;
import com.easipass.commons.lang.text.JsonUtils;
import com.easipass.commons.lang.text.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
@Transactional
public class MyNoteServiceImpl implements MyNoteService {

    @Autowired
    MyNoteDao myNoteDao;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public List<MyNotesPO> getAllNotes() {
        return myNoteDao.getAll(9);
    }

    @Override
    public boolean addNote(MyNotesDTO myNotesDTO) {
        String format = sdf.format(new Date());
        MyNotesPO myNotesPO = JsonUtils.beanToBean(myNotesDTO, MyNotesPO.class);
        UUID uuid = UUID.randomUUID();
        if (StringUtils.isEmpty(myNotesDTO.getTitle())){
            myNotesPO.setTitle(uuid.toString());
        }
        myNotesPO.setId(uuid.toString());
        myNotesPO.setStatus(1);
        myNotesPO.setCreateTime(format);
        myNotesPO.setModifyTime(format);
        myNotesPO.setTimeStamp(new Date().getTime());
        myNoteDao.insert(myNotesPO);
        return true;
    }

    @Override
    public boolean deleteOneNote(String noteId) {
        Optional<MyNotesPO> byId = myNoteDao.findById(noteId);
        if (byId.isPresent()){
            MyNotesPO myNotesPO = byId.get();
            myNotesPO.setStatus(9);
            myNoteDao.update(myNotesPO);
        } else {
            throw new RuntimeException("找不到");
        }
        return true;
    }

    @Override
    public boolean updateNote(MyNotesDTO myNotesDTO) {
        String format = sdf.format(new Date());
        Optional<MyNotesPO> byId = myNoteDao.findById(myNotesDTO.getId());
        if (byId.isPresent()){
            MyNotesPO myNotesPO = byId.get();
            myNotesPO.setNoteInfoJsonStr(myNotesDTO.getNoteInfoJsonStr());
            myNotesPO.setTitle(myNotesDTO.getTitle());
            myNotesPO.setModifyTime(format);
            myNotesPO.setTimeStamp(new Date().getTime());
            myNoteDao.update(myNotesPO);
        } else {
            throw new RuntimeException("找不到");
        }
        return true;
    }
}
